<?php

/**
 * 还款计划
 */
class ReturnedmoneyplanController extends Controller_Base
{
    /**
     * 还款计划列表
     */
    public function indexAction()
    {
        $getPage = $this->getRequest()->getQuery('page', 1);
        $status = $this->getRequest()->getQuery('status', '');
        $mediationOrganId = $this->getRequest()->getQuery('mediationOrganId', '');
        $litigantName = trim($this->getRequest()->getQuery('litigantName', ''));
        $caseId = trim($this->getRequest()->getQuery('caseId', ''));
        $assetsId = trim($this->getRequest()->getQuery('assetsId', ''));
        $repaymentDate = trim($this->getRequest()->getQuery('repaymentDate', ''));
        $mediatorId = trim($this->getRequest()->getQuery('mediatorId', ''));
        $batshId = trim($this->getRequest()->getQuery('batshId', ''));
        $importRecordId = trim($this->getRequest()->getQuery('importRecordId', ''));
        $limit = trim($this->getRequest()->getQuery('limit', 10));

        $page = $getPage ? $getPage : 1;
        $start = ($page - 1) * $limit;

        $where = $this->getWhere();
        if ($status) {
            array_push($where, "status='{$status}'");
        }
        if ($litigantName) {
            array_push($where, "litigantName='{$litigantName}'");
        }
        if ($caseId) {
            array_push($where, "caseId='{$caseId}'");
        }
        if ($assetsId) {
            array_push($where, "assetsId='{$assetsId}'");
        }
        if ($assetsId) {
            array_push($where, "assetsId='{$assetsId}'");
        }
        if ($repaymentDate) {
            array_push($where, "repaymentDate='{$repaymentDate}'");
        }
        if ($mediatorId) {//按照案件号查询
            array_push($where, "mediatorId = '{$mediatorId}'");
        }
        if ($batshId) {//按照案件号查询
            array_push($where, "batshId = '{$batshId}'");
        }
        if ($importRecordId) {//按照案件号查询
            array_push($where, "importRecordId = {$importRecordId}");
        }
        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => $start,
            'order' => 'repaymentDate ASC , `id` ASC'
        );

        $list = Module_Mediate_ReturnedMoneyPlan::getInstance()->getAllBySearch(array("*"), $seacher, true);
        $totalres = Module_Mediate_ReturnedMoneyPlan::getInstance()->getAllBySearch(array("count(*) as num",'sum(repaidAmount) as totalrepaidAmount','sum(repayAmount) as totalrepayAmount'), array('where' => $where), true);

        $total = $totalres[0]['num'];
        $totalrepaidAmount = $totalres[0]['totalrepaidAmount'];
        $totalrepayAmount = $totalres[0]['totalrepayAmount'];

        $page_query = [
            'status' => $status,
            'mediationOrganId' => $mediationOrganId,
            'caseId' => $caseId,
            'mediatorId' => $mediatorId,
            'litigantName' => $litigantName,
            'repaymentDate' => $repaymentDate,
            'assetsId' => $assetsId,
            'batshId' => $batshId,
            'importRecordId' => $importRecordId,
            'limit' => $limit,
        ];
        $this->getMediationOrgan();
        //赋值资产方
        $this ->getAssets();
        $this_start_date = strtotime(date('Y-m-01 00:00:00'));
        $this_end_date = strtotime(date('Y-m-t 23:59:59'));
        $next_start_date = strtotime("first day of next month 00:00:00");
        $next_end_date = strtotime("last day of next month 23:59:59");
        $totalwhere = [];
        if($where){
            foreach ($where as $val){
                $totalwhere[] = 'returned_money_plan.'.$val;
            }
        }
        $detail = [];
        if($list){
            $planIds = implode(',',array_column($list,'id'));
            $thisTotalwhere = $totalwhere;
            $thisTotalwhere[] = "returned_money_plan_detail.repaymentDate >= $this_start_date and returned_money_plan_detail.repaymentDate < $this_end_date";
            $this_totalres = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(array('sum(returned_money_plan_detail.realRepayAmount) as totalrealRepayAmount','sum(returned_money_plan_detail.repayAmount) as totalrepayAmount'), array('where' => $thisTotalwhere,'join'=>'left join returned_money_plan on returned_money_plan_detail.planId=returned_money_plan.id'), true);
            $nextTotalwhere[] = "returned_money_plan_detail.repaymentDate >= $next_start_date and returned_money_plan_detail.repaymentDate < $next_end_date";
            $naxt_totalres = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(array('sum(returned_money_plan_detail.repayAmount) as totalrepayAmount'), array('where' => $nextTotalwhere,'join'=>'left join returned_money_plan on returned_money_plan_detail.planId=returned_money_plan.id'), true);
            $detailwhere[] = "planId in ({$planIds}) and returned_money_plan_detail.repaymentDate >= $this_start_date and returned_money_plan_detail.repaymentDate < $next_end_date";
            $planDetail = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(array('returned_money_plan_detail.id,returned_money_plan_detail.repayAmount,returned_money_plan_detail.realRepayAmount,returned_money_plan_detail.realRepayAmount,returned_money_plan_detail.repaymentDate,returned_money_plan_detail.planId'), array('where' => $detailwhere,'join'=>'left join returned_money_plan on returned_money_plan_detail.planId=returned_money_plan.id'), true);

            $detail = [];
            foreach ($planDetail as $val){
                if($val['repaymentDate'] < $this_end_date){
                    $detail[$val['planId']]['this']['repayAmount'] = $val['repayAmount'];
                    $detail[$val['planId']]['this']['isRepay'] = $val['realRepayAmount'] > 0 ? 1 : 0;
                }else{
                    $detail[$val['planId']]['next']['repayAmount'] = $val['repayAmount'];
                }
            }

        }
        $this->getMediator();

        SmartyAdapter::assign('this_realRepayAmount', empty($this_totalres[0]['totalrealRepayAmount']) ? 0 : $this_totalres[0]['totalrealRepayAmount']);
        SmartyAdapter::assign('this_repayAmount', empty($this_totalres[0]['totalrepayAmount']) ? 0 : $this_totalres[0]['totalrepayAmount']);
        SmartyAdapter::assign('next_realRepayAmount', empty($naxt_totalres[0]['totalrepayAmount']) ? 0 : $naxt_totalres[0]['totalrepayAmount']);


        SmartyAdapter::assign('repayStatusArr', Module_Mediate_Case::$repayStatusArr);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('totalrepaidAmount', $totalrepaidAmount);
        SmartyAdapter::assign('totalrepayAmount', $totalrepayAmount);

        SmartyAdapter::assign('totalPage', ceil($total / $limit));

        SmartyAdapter::assign('query', $page_query);

        SmartyAdapter::assign('list', $list);
        SmartyAdapter::assign('detail', $detail);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('page_query', http_build_query($page_query));
        SmartyAdapter::$templateName = 'returnedmoneyplan/index';
    }

    public function planexportAction()
    {
        $status = $this->getRequest()->getQuery('status', '');
        $mediationOrganId = $this->getRequest()->getQuery('mediationOrganId', '');
        $litigantName = trim($this->getRequest()->getQuery('litigantName', ''));
        $caseId = trim($this->getRequest()->getQuery('caseId', ''));
        $where = $this->getWhere();
        if ($status) {
            array_push($where, "status='{$status}'");
        }
        if ($litigantName) {
            array_push($where, "litigantName='{$litigantName}'");
        }
        if ($caseId) {
            array_push($where, "caseId='{$caseId}'");
        }
        $seacher = array(
            'where' => $where,
            'order' => 'id DESC'
        );
        $repayStatusArr = Module_Mediate_Case::$repayStatusArr;
        $list = Module_Mediate_ReturnedMoneyPlan::getInstance()->getAllBySearch(array("*"), $seacher, true);
        $assets = array_column(
            Module_InfoBase_Assets::getInstance()->getAllBySearch(
                ['id','name'],
                [],
                true
            ),
            'name',
            'id');
        $data=[];
        if (!empty($list)) {
            $this->getMediationOrgan();
            $mediationOrgan= SmartyAdapter::getTplVars('mediationOrgan');
            foreach ($list as $k => $v) {
                $data[$k]['mediationOrganId'] = $mediationOrgan[$v['mediationOrganId']]['name'];
                $data[$k]['caseId'] = $v['caseId'];
                $data[$k]['assets'] = $assets[$v['assetsId']];
                $data[$k]['importRecordId'] = $v['importRecordId'];
                $data[$k]['batshId'] = $v['batshId'];
                $data[$k]['litigantName'] = $v['litigantName'];
                $data[$k]['mediatorName'] = $v['mediatorName'];
                $data[$k]['status'] = $repayStatusArr[$v['status']];
                $data[$k]['repayAmount'] = $v['repayAmount'];
                $data[$k]['repaidAmount'] = $v['repaidAmount'];
                $data[$k]['numberOfPayments'] = $v['numberOfPayments'];
                $data[$k]['numberOfRepaid'] = $v['numberOfRepaid'];
                $data[$k]['repaymentDate'] = "每月".$v['repaymentDate'].'日';
                $data[$k]['addTime'] = !empty($v['addTime'])?date("Y-m-d",$v['addTime']):'';
            }

        }
        $header = array( '调解组','案件号','资产方','导入批次id','案件标识号','当事人', '添加人', '还款状态', '计划金额', '已还金额', '计划期数', '已还期数', '还款日','添加时间');

        Lib_XlsxExport::getInstance()->downExcel($data, $header, '还款计划');
        exit();

    }

    /**
     * 还款详情列表
     */
    public function detailAction()
    {
        $getPage = $this->getRequest()->getQuery('page', 1);
        $status = $this->getRequest()->getQuery('status', '');
        $mediationOrganId = $this->getRequest()->getQuery('mediationOrganId', '');
        $litigantName = trim($this->getRequest()->getQuery('litigantName', ''));
        $caseId = trim($this->getRequest()->getQuery('caseId', ''));
        $planId = trim($this->getRequest()->getQuery('id', ''));
        $assetsId = $this->getRequest()->getQuery('assetsId', 0);
        $realRepaymentDate = intval($this->getRequest()->getQuery('realRepaymentDate_begin_end', 0));

        $limit = 10;
        $page = $getPage ? $getPage : 1;


        $where = $this->getWhere();
        if ($status) {
            array_push($where, "status='{$status}'");
        }
        if ($litigantName) {
            array_push($where, "litigantName='{$litigantName}'");
        }
        if ($caseId) {
            array_push($where, "caseId='{$caseId}'");
        }
        if ($planId) {
            array_push($where, "planId='{$planId}'");
        }
        if ($assetsId) {
            $where = ["assetsId = {$assetsId}"];
            $query['assetsId'] = $assetsId;
        }

        if($realRepaymentDate){
            $date_tmp =  explode(" 到 ",$realRepaymentDate);
            $begin_date = $date_tmp[0];
            $end_date = $date_tmp[1];
            if (!empty($begin_date) || !empty($end_date)) {
                $begin_date = $begin_date ? $begin_date . " 00:00:00" : "";
                $end_date = $end_date ? $end_date . " 23:59:59" : "";
            }
            if ($end_date) {
                $end_date = strtotime($end_date);
                array_push($where, "realRepaymentDate <= {$end_date}");

            }
            if ($begin_date) {
                $begin_date = strtotime($begin_date);
                array_push($where, "realRepaymentDate >= {$begin_date}");
            }
            $query['realRepaymentDate_begin_end'] = $realRepaymentDate;

        }
        array_push($where, "isDel=1");
        $seacher = array(
            'where' => $where,
            'order' => 'repaymentDate ASC'
        );

        $list = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(array("*"), $seacher, true);
        $total = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(array("count(*) as num"), array('where' => $where), true);

        $total = $total[0]['num'];
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $word = Func_Common::numToWord($k + 1);
                $list[$k]['idTmp'] = "第{$word}期";
            }
        }
        $page_query = [
            'status' => $status,
            'mediationOrganId' => $mediationOrganId,
            'caseId' => $caseId,
            'id' => $planId,
            'litigantName' => $litigantName,
        ];
        //赋值调解部门
        $this ->getMediationOrgan();
        //赋值资产方
        $this ->getAssets();
        SmartyAdapter::assign('planStatusArr', Module_Mediate_Case::$planStatusArr);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('totalnum', $total);

        SmartyAdapter::assign('totalPage', ceil($total / $limit));

        SmartyAdapter::assign('query', $page_query);

        SmartyAdapter::assign('list', $list);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('page_query', http_build_query($page_query));
        SmartyAdapter::$templateName = 'returnedmoneyplan/detail';
    }

    /*
     * 还款详情上传凭证
     */
    public function detailEditUploadAction()
    {
        $detail_id = $this->getRequest()->getPost('detail_id', 0);
        $historyFilePath = $this->getRequest()->getPost('filePath', '');
        $file = $this->getRequest()->getFiles('file');

        if (!$detail_id) {
            AjaxTool::returnJsonData(400, '缺少参数');
        }
        $planDetail = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getItemById($detail_id);
        if (empty($planDetail)) {
            AjaxTool::returnJsonData(400, '查询不到案件信息');
        }
        if (in_array($planDetail['status'], ['wait_plan', 'finish_plan'])) {
            AjaxTool::returnJsonData(400, '待审核或审核通过状态,能不能上传凭证');
        }
        if (!$planDetail['caseId']) {
            AjaxTool::returnJsonData(400, '缺少案件信息id');
        }
        $realRepaymentDate = $this->getRequest()->getPost('realRepaymentDate', '');
        $realRepayAmount = $this->getRequest()->getPost('realRepayAmount', '');
        $notes = $this->getRequest()->getPost('notes', '');

        if (!$realRepaymentDate) {
            AjaxTool::returnJsonData(400, '请填写实际还款时间');
        }
        if (!$realRepayAmount || !is_numeric($realRepayAmount)) {
            AjaxTool::returnJsonData(400, '请填写实际还款金额');
        }
        $res = preg_match("/^[0-9]+(.[0-9]{0,2})$/", $realRepayAmount);
        if (!$res) {
            AjaxTool::returnJsonData(400, '实际还款金额请保留2位小数');
        }

        $data['realRepaymentDate'] = strtotime($realRepaymentDate);
        $data['realRepayAmount'] = $realRepayAmount;
        if($notes){
            $data['notes'] = $this->my_addslashes($notes);
        }

        if(!empty($file)){

            if ($file['error'] != 4) {
                $path = 'repayEvidence/' . md5($planDetail['caseId']) . '/';
                Func_Log::write('uploadRepayEvidence', '上传id:' . $planDetail['caseId'], 'path:' . $path);

                $fileName = time() . rand(1, 1000);
                $uploadFile = Lib_Upload::getInstance()->uploadFile($file, $path, 1, $fileName);
                if (!$uploadFile || $uploadFile['code']) {
                    AjaxTool::returnJsonData(400, $uploadFile['msg']);
                }
                $data['filepath'] = trim($uploadFile['data'], '/upload');
            } else {
                AjaxTool::returnJsonData(400, '文件不能为空');
            }
        }

        $ts = time();

        if ($detail_id) {
            $data['updateTime'] = $ts;
            $data['id'] = $detail_id;
            $data['status'] = 'wait_plan';//上传凭证 自动变成待审核,
            $res = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->singleUpdate($data, 'id');
            if (!$res) {
                AjaxTool::returnJsonData(400, '操作成功');
            }

            //操作日志
            $insertdata = array(
                'caseId' => $planDetail['caseId'],
                'status' => "entry_repay",
                'operationUid' => $this->admin['id'],
                'operationName' => $this->admin['name'],
                'operationContent' => '上传提交还款凭证',
                'createTime' => time(),
            );
            Module_Mediate_CaseOperationLog::getInstance()->insert($insertdata);
        }

        AjaxTool::returnJsonData(200, '操作成功');
    }

    /*
     * 还款详情修改
     */
    public function detailEditAction()
    {
        $detail_id = $this->getRequest()->getPost('detail_id', 0);
        if (!$detail_id) {
            AjaxTool::returnJsonData(400, '缺少参数');
        }
        $planDetail = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getItemById($detail_id);
        if (empty($planDetail)) {
            AjaxTool::returnJsonData(400, '查询不到案件信息');
        }
        if (!$planDetail['caseId']) {
            AjaxTool::returnJsonData(400, '缺少案件信息id');
        }
        if (in_array($planDetail['status'], [ 'finish_plan'])) {
            AjaxTool::returnJsonData(400, '待审核或审核通过状态,能不能进行修改');
        }
        $repaymentDate = $this->getRequest()->getPost('repaymentDate', '');
        $repayAmount = $this->getRequest()->getPost('repayAmount', '');

        if (!$repaymentDate) {
            AjaxTool::returnJsonData(400, '请填写还款时间');
        }
        if (!$repayAmount || !is_numeric($repayAmount)) {
            AjaxTool::returnJsonData(400, '请填写还款金额');
        }

        $res = preg_match("/^[0-9]+(.[0-9]{2})$/", $repayAmount);
        if (!$res) {
            AjaxTool::returnJsonData(400, '实际还款金额请保留2位小数');
        }

        $data['repaymentDate'] = strtotime($repaymentDate);
        $data['repayAmount'] = $repayAmount;

        $ts = time();

        if ($detail_id) {
            $data['updateTime'] = $ts;
            $data['id'] = $detail_id;
            $res = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->singleUpdate($data, 'id');
            if (!$res) {
                AjaxTool::returnJsonData(400, '操作成功');
            }

            //操作日志
            $insertdata = array(
                'caseId' => $planDetail['caseId'],
                'status' => "entry_repay",
                'operationUid' => $this->admin['id'],
                'operationName' => $this->admin['name'],
                'operationContent' => '修改还款计划详情',
                'createTime' => time(),
            );
            Module_Mediate_CaseOperationLog::getInstance()->insert($insertdata);
        }

        AjaxTool::returnJsonData(200, '操作成功');
    }

    /**
     * 新增还款详情
     */
    public function detailAddAction()
    {
        $plan_id = $this->getRequest()->getPost('plan_id', 0);
        if (!$plan_id) {
            AjaxTool::returnJsonData(400, '缺少参数');
        }
        $plan = Module_Mediate_ReturnedMoneyPlan::getInstance()->getItemById($plan_id);
        if (empty($plan)) {
            AjaxTool::returnJsonData(400, '查询不到案件信息');
        }

        $repaymentDate = $this->getRequest()->getPost('repaymentDate', '');
        $repayAmount = $this->getRequest()->getPost('repayAmount', '');

        if (!$repaymentDate) {
            AjaxTool::returnJsonData(400, '请填写还款时间');
        }
        if (!$repayAmount || !is_numeric($repayAmount)) {
            AjaxTool::returnJsonData(400, '请填写还款金额');
        }


        $res = preg_match("/^[0-9]+(.[0-9]{0,2})$/", $repayAmount);
        if (!$res) {
            AjaxTool::returnJsonData(400, '实际还款金额请保留2位小数');
        }


        $ts = time();

        $data['planId'] = $plan_id;
        $data['mediatorId'] = $this->admin['id'];
        $data['mediatorName'] = $this->admin['name'];
        $data['mediationOrganId'] = $this->admin['mediationOrganId'];
        $data['assetsId'] = $plan['assetsId'];
        $data['litigantName'] = $plan['litigantName'];;
        $data['caseId'] = $plan['caseId'];
        $data['status'] = 'keep_plan';
        $data['repaymentDate'] = strtotime($repaymentDate);
        $data['repayAmount'] = $repayAmount;
        $data['addTime'] = $ts;
        $data['updateTime'] = $ts;

        $res = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->singleInsert($data);
        if (!$res) {
            AjaxTool::returnJsonData(400, '操作成功');
        }

        //操作日志
        $insertdata = array(
            'caseId' => $plan['caseId'],
            'status' => "entry_repay",
            'operationUid' => $this->admin['id'],
            'operationName' => $this->admin['name'],
            'operationContent' => '新增还款计划详情,还款时间:'.$repaymentDate.",还款金额：".$repayAmount,
            'createTime' => time(),
        );
        Module_Mediate_CaseOperationLog::getInstance()->insert($insertdata);


        AjaxTool::returnJsonData(200, '操作成功');
    }

    /*
     * 还款审核列表
     */
    public function checklistAction()
    {
        $getPage = $this->getRequest()->getQuery('page', 1);
        $status = $this->getRequest()->getQuery('status', 'wait_plan');
        $mediationOrganId = $this->getRequest()->getQuery('mediationOrganId', '');
        $litigantName = trim($this->getRequest()->getQuery('litigantName', ''));
        $caseId = trim($this->getRequest()->getQuery('caseId', ''));
        $limit = trim($this->getRequest()->getQuery('limit', 10));

        $page = $getPage ? $getPage : 1;
        $start = ($page - 1) * $limit;

        $where = $this->getWhere();
        if ($status) {
            array_push($where, "status='{$status}'");
        }
        if ($litigantName) {
            array_push($where, "litigantName='{$litigantName}'");
        }
        if ($caseId) {
            array_push($where, "caseId='{$caseId}'");
        }

        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => $start,
            'order' => 'id DESC'
        );

        $list = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(array("*"), $seacher, true);
        $total = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(array("count(*) as num"), array('where' => $where), true);

        $total = $total[0]['num'];

        $page_query = [
            'status' => $status,
            'mediationOrganId' => $mediationOrganId,
            'caseId' => $caseId,
            'litigantName' => $litigantName,
            'limit' => $limit,
        ];

        //assign

        $this->getMediationOrgan();

        SmartyAdapter::assign('planStatusArr', Module_Mediate_Case::$planStatusArr);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('totalnum', $total);

        SmartyAdapter::assign('totalPage', ceil($total / $limit));

        SmartyAdapter::assign('query', $page_query);

        SmartyAdapter::assign('list', $list);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('page_query', http_build_query($page_query));
        SmartyAdapter::$templateName = 'returnedmoneyplan/checklist';
    }

    /*
     * 还款审核
     */
    public function checkStatusAction()
    {
        $detail_id = $this->getRequest()->getPost('detail_id', 0);
        $check_status = $this->getRequest()->getPost('check_status', '');
        $notesCheck = $this->getRequest()->getPost('notesCheck', '');
        if (!$detail_id) {
            AjaxTool::returnJsonData(400, '缺少参数');
        }
        $planDetail = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getItemById($detail_id);
        if (empty($planDetail)) {
            AjaxTool::returnJsonData(400, '查询不到案件信息');
        }
        if (!$planDetail['caseId']) {
            AjaxTool::returnJsonData(400, '缺少案件信息id');
        }
        if(empty($check_status)){
            AjaxTool::returnJsonData(400, '请选择审核状态');
        }
        if ($check_status == 'reject_plan' && !$notesCheck) {
            AjaxTool::returnJsonData(400, '当驳回时，填写审核备注');
        }
        $data['status'] = $check_status;
        if($notesCheck){
            $data['notesCheck'] = $this->my_addslashes($notesCheck);
        }

        $ts = time();

        if ($detail_id) {
            $data['updateTime'] = $ts;
            $data['id'] = $detail_id;
            $res = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->singleUpdate($data, 'id');
            if (!$res) {
                AjaxTool::returnJsonData(400, '操作失败');
            }
            //如果修改为已还的状态,去修改ReturnedMoneyPlan 表repaidAmount 已还期数
            $num = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(['count(*) as numberOfRepaid, sum(realRepayAmount) as amount'], ["where" =>["status='finish_plan'","planId = {$planDetail['planId']}"]]);
            $planSave =  [
                'numberOfRepaid' => $num[0]['numberOfRepaid'],
                'repaidAmount' => $num[0]['amount'],
                'id' => $planDetail['planId'],
                'updateTime' => $ts
            ];
            //查询是否有未还款的
            $noRepayNum = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(['count(id) as num'], ["where" =>["status='keep_plan'","planId = {$planDetail['planId']}"]]);
            if ($check_status == 'finish_plan'){
                if($noRepayNum[0]['num'] == 0){
                    $planSave['status'] = 'finish_repay';
                }else{
                    $planSave['status'] = 'keep_repay';

                }
            }
            //每次修改  已还期数
            Module_Mediate_ReturnedMoneyPlan::getInstance()->singleUpdate($planSave);
            //修改案件还款状态
            Module_Mediate_case::getInstance()->singleUpdate([
                'id'=>$planDetail['caseId'],
                'repayStatus'=>$planSave['status'],
            ]);
            //操作日志
            $insertdata = array(
                'caseId' => $planDetail['caseId'],
                'status' => "entry_repay",
                'operationUid' => $this->admin['id'],
                'operationName' => $this->admin['name'],
                'operationContent' => '审核还款计划',
                'createTime' => time(),
            );
            Module_Mediate_CaseOperationLog::getInstance()->insert($insertdata);
        }

        AjaxTool::returnJsonData(200, '操作成功');
    }


    /*
     * 删除计划详情
     */
    public function deldetailAction()
    {
        $detail_id = $this->getRequest()->getPost('detail_id', 0);

        if (!$detail_id) {
            AjaxTool::returnJsonData(400, '缺少参数');
        }
        $planDetail = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getItemById($detail_id);
        if (empty($planDetail)) {
            AjaxTool::returnJsonData(400, '查询不到案件信息');
        }
        if ($planDetail['status'] == 'finish_plan') {
            AjaxTool::returnJsonData(400, '已完成还款状态不能删除');
        }

        $data = [
            "id" => $detail_id,
            "isDel" => 2,
            "updateTime" => time(),
        ];
        $res = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->singleUpdate($data, 'id');
        if (!$res) {
            AjaxTool::returnJsonData(200, '操作失败');
        }
        //操作日志
        $insertdata = array(
            'caseId' => $planDetail['caseId'],
            'status' => "entry_repay",
            'operationUid' => $this->admin['id'],
            'operationName' => $this->admin['name'],
            'operationContent' => '删除还款计划详情,详情id:'.$detail_id.",计划id：".$planDetail['planId'],
            'createTime' => time(),
        );
        AjaxTool::returnJsonData(200, '操作成功');

    }


    /*
     * 删除还款计划
     */
    public function delplanAction()
    {
        $plan_id = $this->getRequest()->getPost('plan_id', 0);

        if (!$plan_id) {
            AjaxTool::returnJsonData(400, '缺少参数');
        }
        $plan = Module_Mediate_ReturnedMoneyPlan::getInstance()->getItemById($plan_id);
        if(empty($plan)){
            AjaxTool::returnJsonData(400, '找不到还款计划');
        }
        if($this->admin['role_id'] !=1){
            $planDetail = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(['id'],['where'=>["planId={$plan_id}","status in ('wait_plan','finish_plan')"]]);
            if ($planDetail) {
                AjaxTool::returnJsonData(400, '有审核通过或还款完成记录不允许删除');
            }
            if($plan['status'] != 'wait_repay'){
                AjaxTool::returnJsonData(400, '还款计划状态异常，不允许删除');
            }
        }
        //更新案件还款状态
        $res = Module_Mediate_Case::getInstance()->singleUpdate(
            [
                'id'=>$plan['caseId'],
                'repayStatus'=>'no_repay',
            ]
        );
        if(!$res){
            AjaxTool::returnJsonData(400, '案件还款状态更新失败');
        }
        //删除详情
        $res = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->deleteItemById($plan_id,'planId');
        if(!$res){
            AjaxTool::returnJsonData(400, '删除还款计划详情失败');
        }
        //删除详情
        $res = Module_Mediate_ReturnedMoneyPlan::getInstance()->deleteItemById($plan_id);
        if(!$res){
            AjaxTool::returnJsonData(400, '删除还款计划失败');
        }
        $insertdata = array(
            'caseId' => $plan['caseId'],
            'status' => "entry_repay",
            'operationUid' => $this->admin['id'],
            'operationName' => $this->admin['name'],
            'operationContent' => '删除还款计划,计划id:'.$plan_id.',系统案件号：'.$plan['caseId'],
            'createTime' => time(),
        );
        @Module_Mediate_CaseOperationLog::getInstance()->insert($insertdata);
        AjaxTool::returnJsonData(200, '操作成功');

    }


    /*
     * 还款记录
     */
    public function historyAction()
    {
        $getPage = $this->getRequest()->getQuery('page', 1);
        $mediationOrganId = $this->getRequest()->getQuery('mediationOrganId', '');
        $mediatorId = $this->getRequest()->getQuery('mediatorId', '');
        $submit_type = trim($this->getRequest()->getQuery('submit_type', ''));
        $litigantName = trim($this->getRequest()->getQuery('litigantName', ''));
        $caseId = trim($this->getRequest()->getQuery('caseId', ''));
        $assetsId = $this->getRequest()->getQuery('assetsId', 0);
        $realRepaymentDate = $this->getRequest()->getQuery('realRepaymentDate_begin_end', 0);
        $addDateDate = $this->getRequest()->getQuery('addDate_begin_end', 0);
        $limit = trim($this->getRequest()->getQuery('limit', 10));

        $page = $getPage ? $getPage : 1;
        $start = ($page - 1) * $limit;

        if ($submit_type == 2) {
            $this->historyexportAction();
            exit;
        }
        $where = $this->getWhere('returned_money_plan_detail.mediatorId',[],'returned_money_plan_detail.mediationOrganId');
        array_push($where, "returned_money_plan_detail.status='finish_plan'");
        if ($mediatorId) {//按照案件号查询
            array_push($where, "returned_money_plan_detail.mediatorId = '{$mediatorId}'");
        }
        if ($litigantName) {
            array_push($where, "returned_money_plan_detail.litigantName='{$litigantName}'");
        }
        if ($caseId) {
            array_push($where, "returned_money_plan_detail.caseId='{$caseId}'");
        }
        if ($assetsId) {
            array_push($where, "returned_money_plan_detail.assetsId='{$assetsId}'");
        }

        if($addDateDate){
            $date_tmp =  explode(" 到 ",$addDateDate);
            $begin_date = $date_tmp[0];
            $end_date = $date_tmp[1];
            if (!empty($begin_date) || !empty($end_date)) {
                $begin_date = $begin_date ? $begin_date . " 00:00:00" : "";
                $end_date = $end_date ? $end_date . " 23:59:59" : "";
            }
            if ($end_date) {
                $end_date = strtotime($end_date);
                array_push($where, "returned_money_plan_detail.addTime <= {$end_date}");

            }
            if ($begin_date) {
                $begin_date = strtotime($begin_date);
                array_push($where, "returned_money_plan_detail.addTime >= {$begin_date}");
            }

        }
        if($realRepaymentDate){
            $date_tmp =  explode(" 到 ",$realRepaymentDate);
            $begin_date = $date_tmp[0];
            $end_date = $date_tmp[1];
            if (!empty($begin_date) || !empty($end_date)) {
                $begin_date = $begin_date ? $begin_date . " 00:00:00" : "";
                $end_date = $end_date ? $end_date . " 23:59:59" : "";
            }
            if ($end_date) {
                $end_date = strtotime($end_date);
                array_push($where, "returned_money_plan_detail.realRepaymentDate <= {$end_date}");

            }
            if ($begin_date) {
                $begin_date = strtotime($begin_date);
                array_push($where, "returned_money_plan_detail.realRepaymentDate >= {$begin_date}");
            }

        }
        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => $start,
            'order' => 'returned_money_plan_detail.id DESC',
            'join' => 'left join cases on returned_money_plan_detail.caseId = cases.id'
        );

        $list = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(["returned_money_plan_detail.*",'cases.mediationNum',' cases.batshId','cases.overdueMonth'], $seacher, true);
        $total = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(array("count(*) as num",'sum(realRepayAmount) as totalAmount'), array('where' => $where), true);

        $totalAmount = $total[0]['totalAmount'];
        $total = $total[0]['num'];

        $page_query = [
            'mediatorId' => $mediatorId,
            'mediationOrganId' => $mediationOrganId,
            'caseId' => $caseId,
            'litigantName' => $litigantName,
            'assetsId'=>$assetsId,
            'realRepaymentDate_begin_end'=>$realRepaymentDate,
            'limit' => $limit,
        ];
        $this->getMediator();


        //assign

        $this->getMediationOrgan();

        //赋值资产方
        $this ->getAssets();
        SmartyAdapter::assign('planStatusArr', Module_Mediate_Case::$planStatusArr);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('totalAmount', $totalAmount);

        SmartyAdapter::assign('totalPage', ceil($total / $limit));

        SmartyAdapter::assign('query', $page_query);

        SmartyAdapter::assign('list', $list);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('page_query', http_build_query($page_query));
        SmartyAdapter::$templateName = 'returnedmoneyplan/history';
    }

    /**
     * 还款记录导出
     */
    public function historyexportAction()
    {
        $status = $this->getRequest()->getQuery('status', 'finish_plan');
        $litigantName = trim($this->getRequest()->getQuery('litigantName', ''));
        $caseId = trim($this->getRequest()->getQuery('caseId', ''));
        $assetsId = $this->getRequest()->getQuery('assetsId', 0);
        $realRepaymentDate = $this->getRequest()->getQuery('realRepaymentDate_begin_end', 0);
        $where = $this->getWhere('returned_money_plan_detail.mediatorId',[],'returned_money_plan_detail.mediationOrganId');
        if ($status) {
            array_push($where, "returned_money_plan_detail.status='{$status}'");
        }
        if ($litigantName) {
            array_push($where, "returned_money_plan_detail.litigantName='{$litigantName}'");
        }
        if ($caseId) {
            array_push($where, "returned_money_plan_detail.caseId='{$caseId}'");
        }
        if ($assetsId) {
            array_push($where, "returned_money_plan_detail.assetsId='{$assetsId}'");
        }

        if($realRepaymentDate){
            $date_tmp =  explode(" 到 ",$realRepaymentDate);
            $begin_date = $date_tmp[0];
            $end_date = $date_tmp[1];
            if (!empty($begin_date) || !empty($end_date)) {
                $begin_date = $begin_date ? $begin_date . " 00:00:00" : "";
                $end_date = $end_date ? $end_date . " 23:59:59" : "";
            }
            if ($end_date) {
                $end_date = strtotime($end_date);
                array_push($where, "returned_money_plan_detail.realRepaymentDate <= {$end_date}");

            }
            if ($begin_date) {
                $begin_date = strtotime($begin_date);
                array_push($where, "returned_money_plan_detail.realRepaymentDate >= {$begin_date}");
            }

        }
        $seacher = array(
            'where' => $where,
            'order' => 'returned_money_plan_detail.id DESC',
            'join' => 'left join cases on returned_money_plan_detail.caseId = cases.id'
        );

        $list = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->getAllBySearch(["returned_money_plan_detail.*",'cases.mediationNum',' cases.batshId','cases.overdueMonth'], $seacher, true);
        $data=[];
        if (!empty($list)) {
            $planStatusArr = Module_Mediate_Case::$planStatusArr;
            $this->getMediationOrgan();
            $mediationOrgan= SmartyAdapter::getTplVars('mediationOrgan');
            $assets= array_column(
                Module_InfoBase_Assets::getInstance()->getAllBySearch(
                    ['id','name'],
                    [],
                    true
                ),
                null,
                'id');
            foreach ($list as $k => $v) {
                $data[$k]['mediationNum'] = $v['mediationNum'];
                $data[$k]['batshId'] = $v['batshId'];
                $data[$k]['mediationOrganId'] = $mediationOrgan[$v['mediationOrganId']]['name'];
                $data[$k]['assetsId'] = $assets[$v['assetsId']]['name'];
                $data[$k]['mediatorName'] = $v['mediatorName'];
                $data[$k]['status'] = $planStatusArr[$v['status']];
                $data[$k]['repayAmount'] = $v['repayAmount'];
                $data[$k]['repaymentDate'] = !empty($v['repaymentDate'])?date("Y-m-d",$v['repaymentDate']):'';
                $data[$k]['realRepayAmount'] = $v['realRepayAmount'];
                $data[$k]['realRepaymentDate'] = !empty($v['realRepaymentDate'])?date("Y-m-d",$v['realRepaymentDate']):'';
                $data[$k]['overdueMonth'] = 'M'.$v['overdueMonth'];
                $data[$k]['addTime'] = !empty($v['addTime'])?date("Y-m-d",$v['addTime']):'';
                $data[$k]['notes'] = $v['notes'];
            }

        }
        $header = array('调解案号', '案件标识号', '调解组',  '资产方', '添加人', '审核状态', '预计还款金额', '预计还款时间', '实际还款金额', '实际还款时间', '逾期期数M','添加时间', '备注');

        Lib_XlsxExport::getInstance()->downExcel($data, $header, '还款记录');
        exit();

    }
    /**
     * 转移还款记录
     */
    public function transferPlanAction()
    {
        $request = $this->getRequest();
        //案件id
        $id_str = $request->getPost('transfer_plan_ids', '');
        $mediators_id = $request->getPost('mediators_id', '');
        if (!$id_str || empty($mediators_id)) {
            AjaxTool::returnJsonData(4005);
        }
        if (!empty($mediators_id)) {
            $mediator = Module_User_Administrator::getInstance()->getItemById($mediators_id);
            if (!$mediator) {
                AjaxTool::returnJsonData(4001);
            }
        }

        Func_Log::write('transferPlan',$this->admin['name'], '转移计划:'.$id_str);
        Module_Mediate_ReturnedMoneyPlan::getInstance()->beginTransaction();
        $planres = Module_Mediate_ReturnedMoneyPlan::getInstance()->saveByIds([
            'mediatorId'=>$mediators_id,
            'mediationOrganId'=>$mediator['mediationOrganId'],
            'mediatorName'=>$mediator['name'],
            'updateTime'=>time(),
        ],$id_str);
        if (!$planres) {
            Module_Mediate_ReturnedMoneyPlan::getInstance()->rollback();
            AjaxTool::returnJsonData(400, "转移失败");
        }
        $res = Module_Mediate_ReturnedMoneyPlanDetail::getInstance()->saveByIds([
            'mediatorId'=>$mediators_id,
            'mediationOrganId'=>$mediator['mediationOrganId'],
            'mediatorName'=>$mediator['name'],
            'updateTime'=>time(),
        ], $id_str,[],'planId');
        if (!$res && $res !== 0) {
            Module_Mediate_ReturnedMoneyPlan::getInstance()->rollback();
            AjaxTool::returnJsonData(400, "修复记录删除失败");
        }
        Module_Mediate_ReturnedMoneyPlan::getInstance()->commit();
        AjaxTool::returnJsonData(200, '成功转交' . $planres . '笔还款计划');

    }

}
